package com.itcast.donkey.fragments;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.itcast.donkey.R;
import com.itcast.donkey.adapters.InHeadLikeAdapter;
import com.itcast.donkey.modles.TravelInHeadLikeModels;
import com.itcast.donkey.modles.UriModles;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/9/12.
 */
public class InHeadLikeFragment extends Fragment {
    private XRecyclerView xRecyclerView;
    private List<TravelInHeadLikeModels> likeModels = new ArrayList<>();
    private List<TravelInHeadLikeModels> templikeModels = new ArrayList<>();
    private int page = 1;
    private InHeadLikeAdapter adapter;
    private SharedPreferences sp;
    private String headID;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_in_head_like, null);
        xRecyclerView = (XRecyclerView) view.findViewById(R.id.xRecyclerView);

        GridLayoutManager gm = new GridLayoutManager(getActivity(), 3);
        gm.setOrientation(LinearLayoutManager.VERTICAL);
        xRecyclerView.setLayoutManager(gm);

        xRecyclerView.setRefreshProgressStyle(22);
        xRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                initData();
            }

            @Override
            public void onLoadMore() {
                page++;
                initData();
            }
        });

        sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
        headID = sp.getString("headimage", "22");

        initData();
        return view;
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(UriModles.TRAVEL_FRONT_IN_HEAD_LIKE_URL + headID + UriModles.TRAVEL_END_IN_HEAD_LIKE_URL + page)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();

                        try {
                            JSONArray jsonArray = new JSONArray(result);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                TravelInHeadLikeModels like = gson.fromJson(jsonArray.get(i).toString(), TravelInHeadLikeModels.class);
                                templikeModels.add(like);
                            }

                            if (templikeModels.size() > 0) {
                                handler.sendEmptyMessage(1);
                            } else {
                                handler.sendEmptyMessage(0);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    if (page == 1) {
                        likeModels.clear();
                        likeModels.addAll(templikeModels);
                        adapter = new InHeadLikeAdapter(getActivity(), likeModels);
                        xRecyclerView.setAdapter(adapter);

                        xRecyclerView.refreshComplete();
                        templikeModels.clear();
                    } else {
                        templikeModels.addAll(templikeModels);
                        adapter.notifyDataSetChanged();
                        xRecyclerView.loadMoreComplete();
                        templikeModels.clear();
                    }
                    break;
            }
        }
    };


}
